const { autoUpdater } = require('electron-updater');
const { BrowserWindow } = require('electron');
const path = require('path');
const configs = require('../package.json');

var updateWindow = null;
function createUpdateWindow(version, fatherWindow, updateWindowUrl) {
  updateWindow = new BrowserWindow({
    width: 400,
    height: 130,
    parent: fatherWindow,
    modal: true,
    show: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  updateWindow.setMenu(null);
  updateWindow.loadURL(updateWindowUrl);
  updateWindow.webContents.on('did-finish-load', () => {
    updateWindow.setTitle('版本升级' + configs.version + "->" + version);
  });
  // updateWindow.webContents.openDevTools();
}

function handleUpdate(fatherWindow, updateWindowUrl, updateServersUrl) {
  autoUpdater.setFeedURL(updateServersUrl);

  autoUpdater.on('error', function (error) {
    console.log(error);
  });
  autoUpdater.on('checking-for-update', function () {
    console.log('checking-for-update');
  });
  autoUpdater.on('update-available', function (info) {
    createUpdateWindow(info.version, fatherWindow, updateWindowUrl);
  });

  autoUpdater.on('update-not-available', function (info) {
    console.log('update-not-available');
    console.log(info);
  });
  autoUpdater.on('download-progress', function (progressObj) {
    console.log('download-progress');
    console.log(progressObj);
    updateWindow.webContents.send("update-download-progress", progressObj);
  });
  autoUpdater.on(
    'update-downloaded',
    function (
      event,
      releaseNotes,
      releaseName,
      releaseDate,
      updateUrl,
      quitAndUpdate
    ) {
      autoUpdater.quitAndInstall();
    }
  );
  autoUpdater.checkForUpdates();
}

module.exports.handleUpdate = handleUpdate;
